<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\PriDeviceInfo;
use App\Http\Traits\Utils;
use App\Http\Traits\UserPrivilege;
use App\Http\Requests\DeviceinfoRequest;
use DefaultCompany;
use App\Models\DevProtocolForm;


class DeviceinfoController extends Controller {

    use Utils, UserPrivilege;

    /**
     * @api {get} /deviceinfo/ 列表
     * @apiDescription 设备列表
     * @apiGroup 设备管理
     * @apiPermission none
     * @apiParam {Number} [pdi_code] 设备编码
     * @apiParam {Number} [pageSize=15] 每页显示条数 
     * @apiSuccess {String} code 状态标志 
     * @apiSuccess {String} message 提示信息 
     * @apiSuccess {Object[]} data  区域数据
     * @apiSuccessExample {json} 成功:
     *     HTTP/1.1 201
     *     {
     *         "code": 0,
     *         "message": "",
     *          "data": [
     *             {
     *             }
     *          ],
     *          areaName: {}
     *     }
     * @apiErrorExample {json} 失败:
     *     HTTP/1.1 422
     *     {
     *       "code": -1,
     *       "message": "错误提示"
     *     }
     */
    public function index(Request $request) {
		
        $perPage = $request->input('pageSize', 15);
		
		
        $query = PriDeviceInfo::query();

        $name = $request->input('pdi_name', '');
        if (!empty($name)) {
            $query->where('pdi_name', 'like', $name . '%');
        }

        $pdiCode = $request->input('pdi_code', '');
        if (!empty($pdiCode)) {
            $query->where('pdi_code', 'like', $pdiCode . '%');
        }
        
        $typeId = $request->input('dpt_id', '');
        if (!empty($typeId)) {
            $query->where('dpt_id', '=', trim($typeId));
        }
        $pdi = $request->input('pdi_index', '');
        if (!empty($pdi)) {
            $query->where('pdi_index', '=', trim($pdi));
        }
		
		$companyId = $request->input('company', DefaultCompany::getCompanyField());
        if($companyId) {
            $query->where('t_prideviceinfo.Co_ID', '=', trim($companyId));
        }

        $areaId = $request->input('site', '');
        if (!empty($areaId)) {
            $values = explode(',', trim($areaId));
            $query->whereIn('t_prideviceinfo.AreaId', $values);
        }

        $query->with([
            'company' => function($query) {
                $query->select(['Co_ID', 'Co_Name']);
            },
            'area' => function($query) {
               $query->select(['AreaId','AreaName', 'area_text']);
            },
            'types' => function($query) {
                $query->select(['dt_typeid', 'dt_typename', 'dt_typememo']);
            }
        ]);
		
        $uid = $request->input('uid', '');
		
        $query->select(['t_prideviceinfo.*']);
		
        if ($uid) {
            $query->leftJoin('t_warnnotify', function($join)use($uid) {
                $join->on('t_prideviceinfo.pdi_index', '=', 't_warnnotify.pdi_index')
                        ->where('wu_index', '=', $uid);
            });
            $query->addSelect(['wu_index', 'Wn_notifytype']);
        }

        $showPage = $request->input('hasPage');

        if($showPage) {
            $users = $query->paginate($perPage);
        }else{
            $users = $query->get();
        }

        

        return ['data' => $users];
    }

    /**
     * @api {post} /deviceinfo/ 添加
     * @apiDescription 添加设备
     * @apiGroup 设备管理
     * @apiPermission none
     * @apiSuccessExample {json} 成功:
     *     HTTP/1.1 201
     *     {
     *         "code": 0,
     *         "message": "",
     *              
     *     }
     * @apiErrorExample {json} 失败:
     *     HTTP/1.1 422
     *     {
     *       "code": -1,
     *       "message": "添加失败"
     *     }
     */
    public function store(DeviceinfoRequest $request) {
		
        $data = $request->input();
        $ret = PriDeviceInfo::create($data);

        if (!$ret) {
            $this->error('添加失败');
        }
        $this->addAction();
    }

    public function show($id) {
        
    }

    /**
     * @api {put} /deviceinfo/:id 更新
     * @apiDescription 更新设备
     * @apiGroup 设备管理
     * @apiPermission none
     * @apiParam {Number} id 设备编号
     * @apiSuccessExample {json} 成功:
     *     HTTP/1.1 201
     *     {
     *         "code": 0,
     *         "message": "",
     *              
     *     }
     * @apiErrorExample {json} 失败:
     *     HTTP/1.1 422
     *     {
     *       "code": -1,
     *       "message": "保存失败"
     *     }
     */
    public function update(DeviceinfoRequest $request, $id) {
		
        $deviceinfo = PriDeviceInfo::findOrFail($id);
        $data = $request->input();
        $ret = $deviceinfo->update($data);

        if (!$ret) {
            $this->error('保存失败');
        }
        $this->addAction();
    }

    /**
     * @api {delete} /deviceinfo/:id 删除
     * @apiDescription 删除设备
     * @apiGroup 设备管理
     * @apiPermission none
     * @apiParam {Number} id 设备编号
     * @apiSuccessExample {json} 成功:
     *     HTTP/1.1 201
     *     {
     *         
     *          "code": 0,
     *          "message": "",
     *        
     *     }
     * @apiErrorExample {json} 失败:
     *     HTTP/1.1 422
     *     {
     *       "code": -1,
     *       "message": "错误提示"
     *     }
     */
    public function destroy($id) {
        $deviceType = PriDeviceInfo::findOrFail($id);
        if (!$deviceType->delete()) {
            $this->error('删除失败');
        }
        $this->addAction();
    }
    
    /**
     * @api {get} /deviceinfo/devicetype/all 所有设备
     * @apiDescription 获取所有设备
     * @apiGroup 设备管理
     * @apiPermission none
     * @apiSuccessExample {json} 成功:
     *     HTTP/1.1 201
     *     {
     *         
     *          "code": 0,
     *          "data": {
     *              
     *          },
     *        
     *     }
     * @apiErrorExample {json} 失败:
     *     HTTP/1.1 422
     *     {
     *       "code": -1,
     *       "message": "错误提示"
     *     }
     */
    public function getDeviceType() {
        $types = \App\Models\DeviceType::select(['dt_typeid as value', 'dt_typememo as label'])
                ->get()
                ->sortBy('value')
                ->values()
                ->toArray();
        return [ 'data' => $types ];
    }


    /**
     * @api {get} /deviceinfo/:company/area 公司区域
     * @apiDescription 获取公司所有区域
     * @apiGroup 设备管理
     * @apiPermission none
     * @apiParam {Number} id 公司编号
     * @apiSuccessExample {json} 成功:
     *     HTTP/1.1 201
     *     {
     *         
     *          "code": 0,
     *          "data": {
     *              
     *          },
     *        
     *     }
     * @apiErrorExample {json} 失败:
     *     HTTP/1.1 422
     *     {
     *       "code": -1,
     *       "message": "错误提示"
     *     }
     */
    public function getCompanyArea($id) {
        $company = \App\Models\Company::findOrFail($id);
        $areas = $company
                ->areas()
                ->select(['AreaId as value', 'AreaName as label', 'Fid'])
                ->get()
                ->toArray();
        $tree = $this->listToTree($areas, 'value', 'Fid');
        return ['data' => $tree];
    }

    //设备协议
    public function getDeviceProtocol($tid) {
        $list = DevProtocolForm::where('pf_type', $tid)->select(['pf_index', 'pf_des'])->get();

        return ['data' => $list];
    }

}
